import * as API from "../api";
import Base from "./base";

let userInfo = sessionStorage.getItem("user")
  ? JSON.parse(sessionStorage.getItem("user"))
  : null;

class User extends Base {
  get state() {
    return {
      token: "",
      userInfo: userInfo,
      userList: [],
      roleList: [],
      breadcrumb: []
    };
  }
  get actions() {
    return {
      ROLE_LIST_ACTION: async store => {
        let result = await this.get(API.Roles);
        store.commit("ROLE_LIST_COMMIT", result.data.list);
      },
      LOGIN_ACTION: async (store, data) => {
        try {
          let result = await this.post(API.LOGIN, data, true);
          if (result && result.code === 1) {
            store.commit("USER_INFO_COMMIT", result.data);
            sessionStorage.setItem("user", JSON.stringify(result.data));
          }
          return result;
        } catch (error) {
          console.error(error);
        }
      },
      LOGOUT_ACTION: async () => {
        sessionStorage.removeItem("user");
        let result = await this.post(API.LOGOUT, null);
        this.notify(result.code, result.msg);
        return result;
      },
      USER_LIST_ACTION: async store => {
        try {
          let result = await this.get(API.USER);
          if (result && result.code === 1) {
            store.commit("USER_LIST_COMMIT", result.data.list);
          } else {
            store.commit("USER_LIST_COMMIT", []);
          }
        } catch (error) {
          console.error(error);
        }
      },
      USER_CREATE_ACTION: async (store, payload) => {
        try {
          let result = await this.post(API.USER, payload);
          if (result && result.code === 1) {
            this.notify(1, "注册用户成功！");
          } else {
            this.notify(0, "注册用户失败！");
          }
          return result;
        } catch (error) {
          console.error(error);
        }
      },
      USER_DELETE_ACTION: async (store, payload) => {
        try {
          let result = await this.delete(API.USER + "/" + payload);
          if (result && result.code === 1) {
            this.notify(1, "删除用户成功！");
          } else {
            this.notify(0, "删除用户失败！");
          }
          return result;
        } catch (error) {
          console.error(error);
        }
      }
    };
  }
  get mutations() {
    return {
      USER_INFO_COMMIT(state, payload) {
        state.token = payload.token;
        state.userInfo = payload;
      },
      USER_LIST_COMMIT(state, payload) {
        state.userList = payload;
      },
      ROLE_LIST_COMMIT(state, payload) {
        state.roleList = payload;
      },
      BREADCRUMB_COMMIT(state, payload) {
        state.breadcrumb = payload;
      }
    };
  }
  get getters() {
    return {
      userList: state => state.userList,
      userInfo: state => state.userInfo,
      roleList: state => state.roleList,
      breadcrumb: state => state.breadcrumb
    };
  }
}

export default new User();
